# -*- coding: utf-8 -*-
#
# Copyright © 2010 Benedikt Eger
#
# This file is part of top-news-buzz.
#
# top-news-buzz is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# top-news-buzz is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with top-news-buzz.  If not, see <http://www.gnu.org/licenses/>.

import os
import logging

from django.conf import settings

from google.appengine.api import memcache

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

from topnewsbuzz.utils import UrlHelper
from topnewsbuzz.config import Config

class MainPage(webapp.RequestHandler):

    template_values = {}
    template_url = '../templates/index.html'

    def get(self):                
        settings.LANGUAGE_CODE=Config.language_code()     
           
        self.urls = UrlHelper(self.request)
        self.template_values.update({'urls' : self.urls,
                                     'request' : self.request})

        self.service()

        self.__include_html_parts()

        path = os.path.join(os.path.dirname(__file__), self.template_url)
        self.response.out.write(template.render(path, self.template_values))

    def head(self):
        self.response.set_status(200)

    def __include_html_parts(self):
        include_files_path = os.path.join(os.path.dirname(__file__), '../templates/includes')
        include_files = os.listdir(include_files_path)
        for include_file in include_files:
            include_file_key = include_file.replace('.', '_') + '_path'
            include_file_path = os.path.join(include_files_path, include_file)
            self.template_values[include_file_key] = include_file_path
            logging.debug('Including %s as %s' % (include_file, include_file_key))



from topnewsbuzz.pages import NewsListPage, NewsArticlePage
from topnewsbuzz.feed import FeedManager
from topnewsbuzz.score import ScoreService
from topnewsbuzz.admin import ConfigAdminPage, FeedAdminPage, MetricAdminPage
from topnewsbuzz.utils import DatastoreCleanupService


application = webapp.WSGIApplication([('/feeds', FeedManager),
                                      ('/score', ScoreService),
                                      ('/cleanup', DatastoreCleanupService),
                                      ('/admin', ConfigAdminPage),
                                      ('/admin/feeds', FeedAdminPage),
                                      ('/admin/metrics', MetricAdminPage),
                                      ('/[^/]{5,}/.*', NewsArticlePage),
                                      ('/', NewsListPage),
                                      ('/.*', NewsListPage)])


def real_main():
    template.register_template_library('topnewsbuzz.templatetags.customfilters')
    run_wsgi_app(application)

def profile_main():
    # profiling stats
    import cProfile, pstats
    prof = cProfile.Profile()
    prof = prof.runctx("real_main()", globals(), locals())
    print "<pre>"
    stats = pstats.Stats(prof)
    stats.sort_stats("cumulative")  # time or cumulative
    stats.print_stats(80)  # 80 = how many to print
    # The rest is optional.
    # stats.print_callees()
    # stats.print_callers()
    print "</pre>"

    # memcache stats
    cache_stats = memcache.get_stats()
    print "<pre>"
    print "    memcache stats:"
    print "    hits:                        %s" % cache_stats['hits']
    print "    misses:                      %s" % cache_stats['misses']
    print "    byte_hits:                   %s" % cache_stats['byte_hits']
    print "    items:                       %s" % cache_stats['items']
    print "    bytes:                       %s" % cache_stats['bytes']
    print "    oldest_item_age:             %s" % cache_stats['oldest_item_age']
    print "    "
    print "    "
    print "</pre>"

# real_main or profile_main
main = real_main

if __name__ == "__main__":
    main()

